package com.jsyso.weixin.api;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.jsyso.jsyso.json.jackson.JsonMapper;
import com.jsyso.jsyso.lang.JStringUtils;
import com.jsyso.jsyso.util.JsMap;

/**
 * 生成带参数的二维码 API
 * @author janjan, xujian_jason@163.com
 *
 */
public class QrcodeAPI extends API {
	protected static String QRCODE_CREATE = "/cgi-bin/qrcode/create?access_token=";
	protected static String SHOWQRCODE = "/cgi-bin/showqrcode?ticket=";
	
	public API create(String appid, String jsonStr) {
		// 获取token
		JsMap resMap = AccessTokenAPI.getAccessToken(appid);
		String accessToken = resMap.get("access_token", String.class);
		if(StringUtils.isNotBlank(accessToken)) {
			this.postData = jsonStr;
			this.url = JStringUtils.newBuilder(API_WEIXIN_QQ_COM, QRCODE_CREATE, accessToken).toString();
			this.method = RequestMethod.POST;
		}
		if(logger.isDebugEnabled()) {
			logger.debug("[生成二维码]jsonStr=" + (jsonStr));
		}
		return this;
	}
	
	/**
     * 创建永久二维码
     * @param sceneId 场景值ID，永久二维码时最大值为100000（目前参数只支持1--100000）
     */
	public API createPermanent(String appid, int sceneId) {
		Map<String, Object> params = new HashMap<String, Object>();
        params.put("action_name", "QR_LIMIT_SCENE");

        Map<String, Object> actionInfo = new HashMap<String, Object>();
        Map<String, Object> scene = new HashMap<String, Object>();
        scene.put("scene_id", sceneId);

        actionInfo.put("scene", scene);
        params.put("action_info", actionInfo);
        return create(appid, JsonMapper.getInstance().toJson(params));
	}
	
	/**
	 * 通过ticket换取二维码地址
	 */
	public static String getShowQrcodeUrl(String ticket) {
		return MP_WEIXIN_QQ_COM + SHOWQRCODE + ticket;
	}

}
